import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class OnlineUser extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("big5");
		String name = request.getParameter("user");
		String pwd = request.getParameter("password");

		if (null == name || null == pwd || name.equals("") || pwd.equals("")) {
			response.sendRedirect("login.html");
		} else {
			HttpSession session = request.getSession();
			User user = (User) session.getAttribute("user");
			if (null == user || !name.equals(user.getName())) {
				user = new User(name);
				session.setAttribute("user", user);// 將對象綁定到Session中，隨後調用user的valueBound方法把用戶名加入到用戶名列表
			}
			response.setContentType("text/html;charset=big5");
			PrintWriter out = response.getWriter();

			out.println("歡迎用戶<b>" + name + "</b>登錄");
			UserList ul = UserList.getInstance();
			out.println("<br>當前在線的用戶列表:<br>");
			Enumeration<String> enums = ul.getUserList();
			int i = 0;
			while (enums.hasMoreElements()) {
				out.println(enums.nextElement());
				out.println("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
				if (++i == 10) {
					out.println("<br>");
				}
			}

			out.println("<br>當前在線的用戶數:" + i);// ul.getUserCount()
			out.println("<p><a href=logout>退出登錄</a>");
			out.close();
		}

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
